# -*- coding: UTF-8 -*-
import requests,base64,json



def main():

    # client_id 为官网获取的AK， client_secret 为官网获取的SK

    host = 'https://aip.baidubce.com/oauth/2.0/token'
    params = {
        'grant_type' : 'client_credentials' ,
        'client_id' : 'dVL6CbuExqDRNtM9aQDxZaZC' ,
        'client_secret' : 'ogHCBPbYMcrzT0NZq9QKlhgthKSl3QNT',

    }
    headers = {
        'Content-Type': 'application/json; charset=UTF-8',
    }
    res = requests.get(url = host, headers = headers,params =  params)


    reqult = eval(res.text)
    post_params = {
        'access_token' : reqult['refresh_token'],
    }
    print (post_params['access_token'])
    # 通用版
    # post_url = r'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'

    # 高精度版
    post_url = r'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic'

    headers = {
        'Content-Type':'application/x-www-form-urlencoded',
    }
    file_name = input('图片文件名：')

    with open(file_name,'rb') as f :
        image = f.read()
    image_base64 = base64.b64encode(image)
    print(image_base64)
    print("*********************************************")
    date = {
        'image':image_base64,
    }

    res = requests.post(url = post_url, params = post_params, data= date)
    res.encoding = 'utf-8'
    print(res.url)
    if res.content:
        print(res.text)
        print('******************************************')
        js = json.loads(res.text)
        for i in range(js.get('words_result_num') if js.get('words_result_num') else 0):
            print(js['words_result'][i]['words'])
if __name__ == "__main__":
    main()